<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  call和apply重写

  <script>
    function randomString() {
      return (
        Math.random.toString(36).substr(3, 6) +
        new Date().getTime().toString(36)
      )
    }
    // 重写call
    Function.prototype.myCall = function (context) {
      if(typeof context === 'object' && typeof context !== null) {
        var prop = randomString()

        var args = []

        for (let i = 1; i < arguments.length; i++) {
          args.push(arguments[i])
        }
        context[prop] = this;

        var res = eval("context[prop](" + args + ")")
        delete context[prop]
        return res
      }
    }

    //重写apply 
    Function.prototype.myApply = function (context) {
      if(typeof context === 'object' && typeof context !== null) {
        var prop = randomString()

        var args = []

        for (let i = 0; i < arguments[1].length; i++) {
          args.push(arguments[1][i])
        }
        
        context[prop] = this;

        var res = eval("context[prop](" + args + ")")
        delete context[prop]
        return res
      }
    }

    function test(a, b) {
      return a + b
    }

    // console.log(test.myCall({}, 1, 2));
    console.log(test.myApply({}, [1, 2]));

  </script>
</body>

</html>